package com.junzhiit.nengji.dao.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import com.bainaeco.framework.base.dao.AbstractBaseDAO;
import com.bainaeco.framework.common.jdbc.StatementParameter;
import com.bainaeco.framework.enums.IsDelete;
import com.junzhiit.nengji.bo.AdvertiseBO;
import com.junzhiit.nengji.dao.AdvertiseDAO;
import com.junzhiit.nengji.model.Advertise;

@Repository
public class AdvertiseDAOImpl extends AbstractBaseDAO<Advertise> implements AdvertiseDAO {

	@Override
	public List<AdvertiseBO> findAll(int pageNumber, int maxPageRow, Advertise advertise) {
		StringBuffer sql = new StringBuffer();
		sql.append("select a.*,t.name 'advertise_type_name' from `advertise` a");
		sql.append(" left join `advertise_type` t on a.advertise_type_id=t.id where a.is_delete=?");

		StatementParameter params = new StatementParameter();
		params.setInt(IsDelete.NO.toIntValue());

		if (StringUtils.isNotBlank(advertise.getAdvertiseTypeId())) {
			sql.append(" and a.advertise_type_id=?");
			params.setString(advertise.getAdvertiseTypeId());
		}

		sql.append(" order by sort desc");

		return queryForPagingList(sql.toString(), AdvertiseBO.class, params, pageNumber, maxPageRow);
	}
	
	@Override
	public AdvertiseBO getAdvertiseById(String id) {
		StringBuffer sql = new StringBuffer();
		sql.append("select a.*,t.name 'advertise_type_name' from `advertise` a");
		sql.append(" left join `advertise_type` t on a.advertise_type_id=t.id where a.is_delete=?");

		StatementParameter params = new StatementParameter();
		params.setInt(IsDelete.NO.toIntValue());

		if (StringUtils.isNotBlank(id)) {
			sql.append(" and a.id=?");
			params.setString(id);
		}

		return query(sql.toString(), AdvertiseBO.class, params);
	}

	@Override
	public Integer getTotalCount(Advertise advertise) {
		StringBuffer sql = new StringBuffer();
		sql.append("select count(id) from `advertise` where is_delete=?");

		StatementParameter params = new StatementParameter();
		params.setInt(IsDelete.NO.toIntValue());

		if (StringUtils.isNotBlank(advertise.getAdvertiseTypeId())) {
			sql.append(" and advertise_type_id=?");
			params.setString(advertise.getAdvertiseTypeId());
		}

		return queryForInt(sql.toString(), params);
	}

	@Override
	public Integer getMaxSort() {
		String sql = "select max(sort) from `advertise`";
		String str = queryForString(sql.toString());
		if (StringUtils.isNotBlank(str)) {
			return Integer.valueOf(str);
		}
		return 0;
	}

}
